package org.example;

import javafx.scene.control.Button;
import javafx.scene.control.TextField;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

public class threadRunnableImages implements Runnable {
    private File isFile;
    private TextField textField;
    private Button chinkAction;

    public threadRunnableImages(File isFile, TextField textField, Button chinkAction) {
        this.isFile = isFile;
        this.textField = textField;
        this.chinkAction = chinkAction;
    }

    public Button getChinkAction() {
        return chinkAction;
    }

    public void setChinkAction(Button chinkAction) {
        this.chinkAction = chinkAction;
    }

    public File getIsFile() {
        return isFile;
    }

    public void setIsFile(File isFile) {
        this.isFile = isFile;
    }

    public TextField getTextField() {
        return textField;
    }

    public void setTextField(TextField textField) {
        this.textField = textField;
    }

    @Override
    public void run() {
        synchronized (threadRunnableImages.class){
           try {
               getChinkAction().setDisable(true);
               System.out.println(Thread.currentThread()+ "创建" + getIsFile().getPath());
               BufferedImage attribute = ImageIO.read(getIsFile());
               BufferedImage bi = new BufferedImage(attribute.getWidth(),attribute.getHeight(),BufferedImage.TYPE_USHORT_565_RGB);
               Graphics2D nodeDiv = (Graphics2D) bi.getGraphics();
               nodeDiv.drawImage(attribute, 0, 0 , null);
               nodeDiv.dispose();
               attribute=null;
               ImageIO.write(bi, "jpg", getIsFile());
               bi.flush();
               bi=null;
               getTextField().setText(getIsFile().getName());
               getChinkAction().setDisable(false);
           }catch (Exception e){
               e.printStackTrace();
           }

        }
    }
    private byte[] readStream(InputStream inStream){
        try {
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream( 5 * 1024 * 1024);
            byte[] buffer = new byte[inStream.available()];
            int len = -1;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            return outSteam.toByteArray();
        }catch (Exception e){}
        return null;
    }
}
